

//allow changing of divs from hidden to shown..
function setIdProperty( id, property, value )
{
    var styleObject = document.getElementById( id );
    if (styleObject != null)
    {
        styleObject = styleObject.style;
        styleObject[ property ] = value;
    }
}

//ajax base
function createRequest() {
  var request = null;
  try {
    request = new XMLHttpRequest();
  } catch (trymicrosoft) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (othermicrosoft) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }

  if (request == null) {
    alert("Error creating request object!");
  } else {
    return request;
  }
}
function makeRequest(url,toWhom) {
	http_request = createRequest();
	
	http_request.onreadystatechange = toWhom;
	http_request.open('GET', url, true);
	http_request.send(null);
}

function createQuery(form)
{
    var elements = form.elements;
    var pairs = new Array();

    for (var i = 0; i < elements.length; i++) {

        if ((name = elements[i].name) && (value = elements[i].value))
            pairs.push(name + "=" + encodeURIComponent(value));
    }

    return pairs.join("&");
}

function completeBugReport() {
	if (bugRequest.readyState == 4) {
		if (bugRequest.status == 200) {
			alert('Your bug report was successfully submitted! Thank you ' + bugRequest.responseText + '!');
			setIdProperty('bugReport','display','none');
			document.getElementById('bugReportDesc').value = '';
		} else {
			alert('There was a problem submitting your bug report.');
		}
	}
}

//bug reporter
var bugRequest = createRequest();
function sendBugReport(uid,report,sid) {
	var contentType = "application/x-www-form-urlencoded; charset=UTF-8";
	var bugData = 'uid=' + encodeURIComponent(uid) + '&PHPSESSID=' + encodeURIComponent(sid) + '&report=' +encodeURIComponent(report) + '&ajax=' + encodeURIComponent("1");
	
	bugRequest.onreadystatechange = completeBugReport;
	bugRequest.open('POST', '/includes/bugReport.php', true);
	bugRequest.setRequestHeader("Content-Type", contentType);
	bugRequest.send(bugData);
}

//ajaxUpdateClient
function editField(name,text,spanName) {
	var object = document.getElementById(spanName);
	var newContents;
	newContents = '<input type="text" class="editInput" name="' + name + '" id="ajaxUpdateInput_'+name+'" value="' + text + '"><input type="button" id="ajaxUpdateButton_'+name+'" value="Save" onClick="javascript:saveField(\'' + name + '\',document.getElementById(\'ajaxUpdateInput_' + name + '\').value,\''+spanName+'\')">';
	object.innerHTML = newContents;
	document.getElementById("ajaxUpdateInput_"+name).select();
}
function saveField(name,text,spanName) {
	//do ajax post here
	var updateButton = document.getElementById("ajaxUpdateButton_" + name);
	var updateInput  = document.getElementById("ajaxUpdateInput_" + name);
	updateInput.disabled = true;
	updateButton.disabled = true;
	updateButton.value = 'Saving...';
	
	http_request = createRequest();	
	http_request.onreadystatechange = function(){updateField(name,text,spanName,http_request)};
	http_request.open('GET', "includes/ajax.php?updateField="+name+"&value="+text, true);
	http_request.send(null);
}
function updateField(name,text,spanName,requestObj) {
	if (requestObj.readyState == 4) {
		if (requestObj.status == 200) {
			responseXML = requestObj.responseXML.documentElement;
			var responseError = responseXML.getElementsByTagName('error')[0].firstChild.data;
			var responseMsg = responseXML.getElementsByTagName('msg')[0].firstChild.data;
			var responseValue = responseXML.getElementsByTagName('value')[0].firstChild.data;
			if(responseError == 0) {
				//update successful
				var responseResult = responseXML.getElementsByTagName('result')[0].firstChild.data;			
				var object = document.getElementById(spanName);
				var newContents;
				newContents = responseResult + '<span class="ajaxEditLink">[ <a href="javascript:editField(\''+name+'\',\'' + responseResult + '\',\''+spanName+'\')">EDIT</a> ]</span>';
				object.innerHTML = newContents;
			} else {
				//update unsuccessful. Tell them why, and set back to editField
				alert(responseMsg);
				editField(name,responseValue,spanName);
			}
		} else {
			alert("An error occurred while saving your change!");
		}
	}
}

//this is for the modify seniority points section
function addPoints() {
	document.getElementById("saveButton").disabled = true;
	document.getElementById("ajaxStatus").innerHTML = "Posting Points...";
	var driver = document.getElementById("seniority_driver").options[document.getElementById("seniority_driver").selectedIndex].value;
	var points = document.getElementById("seniority_points").value;
	var reason = document.getElementById("seniority_reason").value;
	var url = 'includes/ajax.php?points=post&driver=' + driver + '&numpoints=' + points + '&reason=' + reason;
	
	http_request = createRequest();
	http_request.onreadystatechange = function(){results(http_request);};
	http_request.open('GET', url, true);
	http_request.send(null);
	
}

function results (requestObj) {
	if (requestObj.readyState == 4) {
		if (requestObj.status == 200) {
			responseXML = requestObj.responseXML.documentElement;
			var responseError = responseXML.getElementsByTagName('error')[0].firstChild.data;
			var responseMsg = responseXML.getElementsByTagName('msg')[0].firstChild.data;
			var responseTotal = responseXML.getElementsByTagName('total')[0].firstChild.data;
			var points = document.getElementById("seniority_points").value;
			if(points > 0) points = '+' + points;
			if(responseError == 0) {
				var selectedDriver = document.getElementById("seniority_driver").options[document.getElementById("seniority_driver").selectedIndex].text;
				insertOption(selectedDriver + ": " + points + "(" + responseTotal + ")",document.getElementById("seniority_completed"));
				if(document.getElementById("clearFields").checked === true) {
					document.getElementById("seniority_points").value = '';
					document.getElementById("seniority_reason").value = '';
					document.getElementById("seniority_driver").selectedIndex = 0;
				}
			} else {
				alert(responseMsg);
			}
			document.getElementById("ajaxStatus").innerHTML = "";
			document.getElementById("saveButton").disabled = false;
		}
	}
}

function insertOption(addText,x) {
	var y=document.createElement('option');
	y.text=addText
	try {
		x.add(y,null); // standards compliant
	}
	catch(ex) {
		x.add(y); // IE only
	}
}

// jump menu
function MM_jumpMenu(targ,selObj,restore){ //v3.0
	eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
	if (restore) selObj.selectedIndex=0;
}

// workswap board
function permPrompt() {
	document.getElementById('shiftDate').innerHTML = "PERMANENT <input type='hidden' name='perm' value='1'>";
}
function reloadForm() {
	location.reload();
}


function displayTimepoints() {
	var shiftId = document.getElementById("shift").options[document.getElementById("shift").selectedIndex].value;
	var outputDiv = document.getElementById("shiftTimes");
	var extra = '';
	outputDiv.innerHTML = "<p class='basicFont' style='text-align: center; font-size: 14px; font-weight: bold;'><img src='images/ajaxLoad.gif' width=10 height=10> Loading timepoints...</p>";
	
	//send ajax request
	http_request = createRequest();
	http_request.onreadystatechange = function(){postResults(http_request,outputDiv,extra)};
	http_request.open('GET',"includes/ajax.php?task=grabTimepoints&shiftId="+shiftId,true);
	http_request.send(null);
}

function displayShiftDates() {
	var shiftId = document.getElementById("shift").options[document.getElementById("shift").selectedIndex].value;
	var outputDiv = document.getElementById("shiftDate");
	var extra = '';
	outputDiv.innerHTML = "<p class='basicFont' style='text-align: center; font-size: 14px; font-weight: bold;'><img src='images/ajaxLoad.gif' width=10 height=10> Loading shift dates...</p>";
	
	//send ajax request
	http_request = createRequest();
	http_request.onreadystatechange = function(){postResults(http_request,outputDiv,extra)};
	http_request.open('GET',"includes/ajax.php?grabShiftDates="+shiftId,true);
	http_request.send(null);
}

function postResults(requestObj,pageElement,extra) {
	if (requestObj.readyState == 4) {
		if (requestObj.status == 200) {
			pageElement.innerHTML = requestObj.responseText + extra;
		} else {
			alert('There was a problem with the request. Server returned: ' + requestObj.status);
		}
	}
}

function resetPartialPrompt () {
	document.getElementById("shiftTimes").innerHTML = 'Entire Shift <input type="button" value="Workswap Part" onClick="displayTimepoints()">';
	document.getElementById("shiftDate").innerHTML = 'Permanent <input type="hidden" name="permanent" value="1"> <input type="button" value="Pick Temp Date" onClick="displayShiftDates()">';
}

function alertTextWarning () {
	var thisCheckbox = document.getElementById("txtnotify");
	//check if they are checking, or unchecking..
	if(thisCheckbox.checked == true) {
		//prompt the user letting them know they may incur a fee
		var acceptFee = confirm("Using this feature may cause you to incur additional fees from your cellular provider. Are you sure you want to continue?");
		if(acceptFee == false) {
			thisCheckbox.checked = false;
		}
	}
}

